package com.photoeditor.demo.ui.widget.image.watermark;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class WatermarkManager {
    //
    private static final String WATER_MARK_CUSTOM_TEXT_KEY = "WATER_MARK_CUSTOM_TEXT_KEY";
    public static final String DEFAULT_CUSTOM_TEXT = "";
    // 文本的大小，这里特意不使用dp，因为水印的分辨率适配走的是另一套逻辑
    private static final int DEFAULT_FONT_SIZE = 45;
    public static final String DEFAULT_TEXT_TYPE_FACE_PATH = "fonts/Amatic-Bold.ttf";
    // messenger水印路径
    private static final String MESSENGER_CODE_PATH = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()
            + File.separator + "Messenger" + File.separator + "messenger-code.jpg";

    // Snapchat水印存放目录
    private static final String SNAPCHAT_CODE_DIR_PATH = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + File.separator + "Snapchat";
    // Snapchat水印文件名以Snapchat-开头，如：Snapchat-15854564.jpg
    private static final String SNAPCHAT_CODE_FILE_BASE_NAME = "Snapchat-";

    private static final int DEFAULT_WATERMARK_SIZE_WIDTH = 196;
    private static final int DEFAULT_WATERMARK_SIZE_HEIGHT = 140;

    // 普通水印
    private static final int[] NORMAL_WATERMARK_INFO = new int[]{
            R.drawable.ic_no_watermark,
            R.drawable.ic_watermark_cut_1,
            R.drawable.ic_watermark_cut_2,
            R.drawable.ic_watermark_cut_3
    };

    private static final int[] NORMAL_WATERMARK_DEMO_INFO = new int[]{
            R.drawable.ic_no_watermark,
            R.drawable.ic_watermark_show_1,
            R.drawable.ic_watermark_show_2,
            R.drawable.ic_watermark_show_3
    };

    //普通水印的宽和高
    private static final int[][] NORMAL_WATERMARK_SIZE = new int[][]{
            {DEFAULT_WATERMARK_SIZE_WIDTH, DEFAULT_WATERMARK_SIZE_HEIGHT},
            {DEFAULT_WATERMARK_SIZE_WIDTH, 95},
            {DEFAULT_WATERMARK_SIZE_WIDTH, 147},
            {DEFAULT_WATERMARK_SIZE_WIDTH, 147}
    };

    /**
     * 用于保存上次的水印Id
     */
    public static final String PREF_KEY_WATERMARK_ID = "pref_watermark_id";


    private Context mContext;
    private List<Watermark> mAvailableWatermarks;
    private Watermark mCurrentWatermark;
    private OnWatermarkUpdateListener mWatermarkUpdateListener;
    private Watermark mTempWatermark;

    public WatermarkManager(Context context) {
        mContext = context;
        init();
    }

    /**
     * 根据环境创建所有可用水印
     *
     * @return
     */
    private void init() {
        mAvailableWatermarks = new ArrayList<>();
        // 常规水印
        for (int i = 0; i < NORMAL_WATERMARK_INFO.length; i++) {
            if (i == 1) {
                CustomTextWatermark watermark = new CustomTextWatermark();
                watermark.setDemoResId(NORMAL_WATERMARK_DEMO_INFO[i]);
                watermark.setResId(NORMAL_WATERMARK_INFO[i]);
                watermark.setType(Watermark.TYPE_NORMAL);
                watermark.setWidth(NORMAL_WATERMARK_SIZE[i][0]);
                watermark.setHeight(NORMAL_WATERMARK_SIZE[i][1]);
                watermark.setWidthExcludeText(NORMAL_WATERMARK_SIZE[i][0]);
                watermark.setHeightExcludeText(NORMAL_WATERMARK_SIZE[i][1]);
                watermark.setStatisticName(
                        StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_WATERMARK_GENERATE + "watermark_basic_" + (i + 1));
                watermark.generateId();
                watermark.setFontSize(DEFAULT_FONT_SIZE);
                watermark.setFontPath(DEFAULT_TEXT_TYPE_FACE_PATH);

                setWatermarkText(watermark, SpUtils.obtain().getString(WATER_MARK_CUSTOM_TEXT_KEY + watermark.getId(), DEFAULT_CUSTOM_TEXT));
                mAvailableWatermarks.add(watermark);

                // messenger社交水印
                if (FileUtil.checkExist(MESSENGER_CODE_PATH)) {
                    Watermark watermark1 = new Watermark();
                    watermark1.setDemoResId(R.drawable.ic_watermark_show_message);
                    watermark1.setWidth(DEFAULT_WATERMARK_SIZE_WIDTH);
                    watermark1.setHeight(DEFAULT_WATERMARK_SIZE_WIDTH);
                    watermark1.setType(Watermark.TYPE_SOCIAL);
                    watermark1.setFilePath(MESSENGER_CODE_PATH);
                    watermark1.setStatisticName(
                            StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_WATERMARK_GENERATE + "watermark_sns_" + "messenger");
                    watermark1.generateId();
                    mAvailableWatermarks.add(watermark1);
                }

                // Snapchat社交水印,在水印目录下可能同时存在多张水印图片，取最新的一张
                if (FileUtil.checkExist(SNAPCHAT_CODE_DIR_PATH)) {
                    File file = new File(SNAPCHAT_CODE_DIR_PATH);
                    if (file.isDirectory()) {
                        File[] files = file.listFiles();
                        if (files != null) {
                            int targetIndex = -1;
                            long maxFileTime = 0;
                            for (int j = 0; j < files.length; j++) {
                                File currentFile = files[j];
                                if (currentFile == null) {
                                    continue;
                                }
                                String fileName = currentFile.getName();
                                if (TextUtils.isEmpty(fileName)) {
                                    continue;
                                }
                                if (!fileName.startsWith(SNAPCHAT_CODE_FILE_BASE_NAME) || !fileName.endsWith(".jpg")) {
                                    continue;
                                }

                                // 只读取宽高相等的图片，其图片的exif信息中只保留有宽高的属性
                                ExifInterface exif;
                                String imageWidth = null;
                                String imageHeight = null;
                                try {
                                    exif = new ExifInterface(currentFile.getAbsolutePath());
                                    imageWidth = exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
                                    imageHeight = exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (TextUtils.isEmpty(imageHeight) || !TextUtils.equals(imageWidth, imageHeight)) {
                                    continue;
                                }

                                long tempTime = currentFile.lastModified();
                                if (tempTime > maxFileTime) {
                                    maxFileTime = tempTime;
                                    targetIndex = j;
                                }
                            }

                            if (targetIndex != -1) {
                                Watermark watermark2 = new Watermark();
                                watermark2.setWidth(DEFAULT_WATERMARK_SIZE_WIDTH);
                                watermark2.setHeight(DEFAULT_WATERMARK_SIZE_WIDTH);
                                watermark2.setDemoResId(R.drawable.ic_watermark_show_snapchat);
                                watermark2.setType(Watermark.TYPE_SOCIAL);
                                watermark2.setFilePath(files[targetIndex].getAbsolutePath());
                                watermark2.setStatisticName(
                                        StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_WATERMARK_GENERATE + "watermark_sns_" + "snapchat");
                                watermark2.generateId();
                                mAvailableWatermarks.add(watermark2);
                            }
                        }
                    }
                }
            } else {
                Watermark watermark = new Watermark();
                watermark.setDemoResId(NORMAL_WATERMARK_DEMO_INFO[i]);
                watermark.setResId(NORMAL_WATERMARK_INFO[i]);
                watermark.setType(Watermark.TYPE_NORMAL);
                watermark.setWidth(NORMAL_WATERMARK_SIZE[i][0]);
                watermark.setHeight(NORMAL_WATERMARK_SIZE[i][1]);
                watermark.setStatisticName(
                        StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_WATERMARK_GENERATE + "watermark_basic_" + (i + 1));
                watermark.generateId();
                mAvailableWatermarks.add(watermark);
            }

        }

        // 趣味水印


        mCurrentWatermark = getLastUseWatermark();
        if (mCurrentWatermark == null) {
            mCurrentWatermark = mAvailableWatermarks.get(1);
        }
    }

    public Watermark getEmptyWatermark() {
        return mAvailableWatermarks.get(0);//默认第0个为空
    }

    public List<Watermark> getAvailableWatermarks() {
        return mAvailableWatermarks;
    }

    /**
     * 获取上一次使用的水印
     *
     * @return
     */
    private Watermark getLastUseWatermark() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        int id = preferences.getInt(PREF_KEY_WATERMARK_ID, false/*AppVipManager.isVip()*/ ? R.drawable.ic_no_watermark : R.drawable.ic_watermark_show_1);
//        if (!AppVipManager.isVip() && id == R.drawable.ic_no_watermark) {
//            id = R.drawable.ic_watermark_cut_2;
//        }
        for (Watermark watermark : mAvailableWatermarks) {
            if (watermark.getId() == id) {
                return watermark;
            }
        }
        return null;
    }

    /**
     * 保存最后一次使用的水印
     */
    public void saveLastUseWatermark() {
        int id = mCurrentWatermark.getId();
//        if(!AppVipManager.isVip() && id == R.drawable.ic_no_watermark) {
//            //非付费用户不记录空水印
//            return;
//        }
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        preferences.edit().putInt(PREF_KEY_WATERMARK_ID, id).apply();
    }

    /**
     * 是否用来占位的水印，该水印仅供预览，不需要保存
     *
     * @param watermark
     * @return
     */
    @NonNull
    public boolean isPlaceholderWatermark(Watermark watermark) {
        if (watermark == null) {
            return true;
        }
        return watermark.getResId() == R.drawable.ic_no_watermark;
    }

    /**
     * 上一次是否设置了水印
     *
     * @return
     */
    public boolean isWatermarkExist() {
        return !isPlaceholderWatermark(mCurrentWatermark);
    }

    public Watermark getCurrentWatermark() {
        return mCurrentWatermark;
    }

    public void setCurrentWatermark(Watermark watermark) {
        mCurrentWatermark = watermark;
    }

    public Watermark getTempWatermark() {
        return mTempWatermark;
    }

    public void setTempWatermark(Watermark tempWatermark) {
        mTempWatermark = tempWatermark;
    }

    /**
     * 获取水印的bitmap
     *
     * @param watermark
     * @return
     */
    public Bitmap getWatermarkBitmap(Watermark watermark) {
        if (watermark == null) {
            return null;
        }
        Bitmap resBitmap = null;
        if (watermark.getResId() != 0) {
            resBitmap = BitmapFactory.decodeResource(mContext.getResources(), watermark.getResId());
        } else if (FileUtil.checkExist(watermark.getFilePath())) {
            resBitmap = BitmapUtils.decodeSampledBitmapFromFile(watermark.getFilePath(), watermark.getWidth(), watermark.getHeight());
        }
        if (resBitmap == null) {
            return null;
        }
        if (watermark instanceof CustomTextWatermark) {
            if (TextUtils.isEmpty(((CustomTextWatermark) watermark).getCustomText())) {
                return resBitmap;
            }
            float scale = (float) (resBitmap.getWidth() * 1.0 / ((CustomTextWatermark) watermark).getWidthExcludeText());
            int canvasWidth = (int) (watermark.getWidth() * scale);
            int canvasHeight = (int) (watermark.getHeight() * scale);
            Bitmap bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), ((CustomTextWatermark) watermark).getFontPath()));
            paint.setTextSize(((CustomTextWatermark) watermark).getFontSize() * scale);
            paint.setColor(Color.WHITE);
            paint.setShadowLayer(DeviceUtils.dip2px(ComponentContext.getContext(), 2), 0, 2, 0x80000000);
            canvas.drawBitmap(resBitmap, (canvasWidth - resBitmap.getWidth()) / 2, 0, paint);
            Paint.FontMetrics fontMetrics = paint.getFontMetrics();
            int textWidth = (int) paint.measureText(((CustomTextWatermark) watermark).getCustomText());
            canvas.drawText(((CustomTextWatermark) watermark).getCustomText()
                    , (canvasWidth - textWidth) / 2
                    , resBitmap.getHeight() + (canvasHeight - resBitmap.getHeight()) / 2 + (Math.abs(fontMetrics.ascent) - fontMetrics.descent) / 2 - DeviceUtils.dip2px(ComponentContext.getContext(), 2)
                    , paint);
            return bitmap;
        } else {
            return resBitmap;
        }
    }

    /**
     * 设置水印文本
     *
     * @param watermark
     * @param text
     */
    public void setWatermarkText(CustomTextWatermark watermark, String text) {
        if (watermark == null) {
            return;
        }
        if (TextUtils.isEmpty(text)) {
            watermark.setWidth(watermark.getWidthExcludeText());
            watermark.setHeight(watermark.getHeightExcludeText());
        } else {
            Paint fontPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            fontPaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), watermark.getFontPath()));
            fontPaint.setTextSize(watermark.getFontSize());
            int fontHeight = getFontHeight(fontPaint);
            int fontWidth = (int) fontPaint.measureText(text);
            int height = watermark.getHeightExcludeText();
            if (height == 0) {
                height = watermark.getHeight();
            }
            int width = watermark.getWidthExcludeText();
            if (width == 0) {
                width = watermark.getWidth();
            }
            watermark.setHeightExcludeText(height);
            watermark.setWidthExcludeText(width);
            int horizontalPadding = width / 10;
            watermark.setWidth(Math.max(width, fontWidth) + horizontalPadding);
            watermark.setHeight(fontHeight + height);
        }
        watermark.setCustomText(text);
        SpUtils.obtain().save(WATER_MARK_CUSTOM_TEXT_KEY + watermark.getId(), text);

        if (mWatermarkUpdateListener != null) {
            mWatermarkUpdateListener.onWatermarkUpdate();
        }
    }

    private int getFontHeight(Paint paint) {
        if (paint == null) {
            return 0;
        }
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.bottom - fm.top);
    }

    public void setWatermarkUpdateListener(OnWatermarkUpdateListener watermarkUpdateListener) {
        mWatermarkUpdateListener = watermarkUpdateListener;
    }

    public interface OnWatermarkUpdateListener {
        void onWatermarkUpdate();
    }
}
